package com.pb.wkflow.core.handler;

import com.pb.infra.oth.entity.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.query.Query;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义查询类
 * @author 苗益辉
 * @date 2022/4/28 11:03
 */
@Slf4j
@Component
public class QueryHandler {

    /**
     * 调用 camunda 自带查询 并重新返回值
     * @param query camunda 自带查询器
     * @param pageIndex 页码
     * @param pageSize 页数
     * @param queryResultHandler 自定义返回
     * @return PageInfo
     */
    public <T,E> Result commonPageQuery(Query query, int pageIndex, int pageSize,
                                      QueryResultHandler<T,E> queryResultHandler) {
        try{
            int firstResult = (pageIndex - 1) * pageSize;
            List<E> list = query.listPage(firstResult, pageSize);
            List<T> resultList = new ArrayList<>();
            for(E model : list) {
                T item = queryResultHandler.handlerRecord(model);
                resultList.add(item);
            }
            long count = query.count();
            return Result.ok(count, resultList);
        }catch (Exception e) {
            log.error("分页查询报错 {}",e);
        }
        return null;
    }
}
